package org.biubiu0002.baiblog.core.async.listener;

import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Random;

/**
 * @Author: biubiu0002
 * @Date: 2022/8/4 11:27
 **/
@Component
@RabbitListener(queues = "test.queue")
@Slf4j
public class TestListener {
    @RabbitHandler
    public void onMessage(String msg, Channel channel, Message message) throws IOException {
        long deliveryTag = message.getMessageProperties().getDeliveryTag();
        try {
            Boolean isSuccess = new Random().nextBoolean();
            if(!isSuccess){
                throw new RuntimeException("模拟出现异常");
            }
            log.info("[消费成功]");
            channel.basicAck(deliveryTag,false);

        }catch (Exception e){
            log.error("[消费异常]",e);
            if(Boolean.TRUE.equals(message.getMessageProperties().isRedelivered())){
                log.info("[消费拒绝]");
                channel.basicReject(deliveryTag,false);
            }else{
                log.info("[消费重试]");
                channel.basicNack(deliveryTag,false,true);
            }

        }

    }
}
